package com.sduept.chargeRec;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ssssssss.magicapi.Const;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.TioServerHandler;

import com.sduept.i1.I1ClientHandler;
import com.sduept.tool.PrintTool;



/**
 * @author zcg
 */
//@Component
public class CdzlbServerHandler implements TioServerHandler {
	private static Logger logger = LoggerFactory.getLogger(CdzlbServerHandler.class);
   /**
     * 解码：把接收到的ByteBuffer，解码成应用可以识别的业务消息包
     * 总的消息结构：消息头 + 消息体
     * 消息头结构：    4个字节，存储消息体的长度
     * 消息体结构：   对象的json串的byte[]
     */
    @Override
    public CdzlbPacket decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws TioDecodeException {
        if(readableLength < 60) {
            return null;
        }
        buffer.order(ByteOrder.LITTLE_ENDIAN);
    	//0-5：目的MAC地址，终端向分析工具发送数据目的mac为01:02:03:04:05:06；
    	//分析工具向终端发送数据目的mac为07:08:09:0a:0b:0c
        byte[] mac=new byte[6];
        buffer.get(mac);
        if(mac[0]!=7||mac[1]!=8||mac[2]!=9||
        		mac[3]!=10||mac[4]!=11||mac[5]!=12) {
        	logger.error("目的MAC错误,{}-{}",mac,readableLength);
            Tio.close(channelContext, "目的MAC错误");
        	return null;
        }
        CdzlbPacket imPacket = new CdzlbPacket();
        imPacket.setMacAddress(mac);
        buffer.get(mac);
        imPacket.setOriginMac(mac);
        short size=(short) (buffer.getInt() & 0xFFFF);
        if(size<60) {
            logger.error("开始帧头长度<60,size:{}-{}", size,readableLength);
            Tio.close(channelContext, "开始帧头长度<60");
        	return null;        	
        }
        logger.info("recv: " + PrintTool.bytes2hex(buffer.array(), position, size-16));
        imPacket.setPacketLength(size);
        imPacket.setPacketType(buffer.getShort());
        short code = (short) (buffer.getShort() & 0xFFFF);
        logger.info("CODE:{}", code);
        imPacket.setCode(code);
        byte[] message=new byte[8];
        buffer.get(message);
        imPacket.setMessage(message);

        byte[] spare=new byte[10];
        buffer.get(spare);
        imPacket.setSpare(spare);

        imPacket.setComCounter(buffer.getShort());
        imPacket.setPacketNumber(buffer.getShort());
        imPacket.setPacketCounter(buffer.getShort());
        imPacket.setPacketResend(buffer.getShort());
        imPacket.setComResend(buffer.getShort());
        imPacket.setDataLength(buffer.getInt());
        imPacket.setPointLogo(buffer.getShort());

        byte[] spare2=new byte[6];
        buffer.get(spare2);
        imPacket.setSpare2(spare2);

        byte[] data=new byte[size-60];
        buffer.get(data);
        imPacket.setData(data);

        return imPacket;

    }
    /**
     * 编码：把业务消息包编码为可以发送的ByteBuffer
     * 总的消息结构：消息头 + 消息体
     * 消息头结构：    4个字节，存储消息体的长度
     * 消息体结构：   对象的json串的byte[]
     */
    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
        //创建一个新的bytebuffer
        ByteBuffer buffer = ByteBuffer.allocate(((CdzlbPacket)packet).getPacketLength());
        //设置字节序
        buffer.order(ByteOrder.LITTLE_ENDIAN);


        //写入消息体，消息的长度等于60+data的长度
        buffer.put(((CdzlbPacket)packet).getMacAddress());
        buffer.put(((CdzlbPacket)packet).getOriginMac());
        buffer.putInt(((CdzlbPacket)packet).getPacketLength());
        buffer.putShort(((CdzlbPacket)packet).getPacketType());
        buffer.putShort(((CdzlbPacket)packet).getCode());
        buffer.put(((CdzlbPacket)packet).getMessage());
        buffer.put(((CdzlbPacket)packet).getSpare());
        buffer.putShort(((CdzlbPacket)packet).getComCounter());
        buffer.putShort(((CdzlbPacket)packet).getPacketNumber());
        buffer.putShort(((CdzlbPacket)packet).getPacketCounter());
        buffer.putShort(((CdzlbPacket)packet).getPacketResend());
        buffer.putShort(((CdzlbPacket)packet).getComResend());
        buffer.putInt(((CdzlbPacket)packet).getDataLength());
        buffer.putShort(((CdzlbPacket)packet).getPointLogo());
        buffer.put(((CdzlbPacket)packet).getSpare2());


        //写入数据
        if (((CdzlbPacket)packet).getData() != null) {
            buffer.put(((CdzlbPacket)packet).getData());

        }
        return buffer;
//
    }
    /**
     * 处理消息
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
//        Map<String,Object> params = new HashMap<>();
//        params.put("packet", packet);
//        Const.getService().execute("POST","/network/socketServerHandler", params);
//        System.out.println(Arrays.toString(((CdzlbPacket) packet).getCode()));
        logger.info("服务器处理数据");

        short code=((CdzlbPacket) packet).getCode();
        switch(code){
            case 0x40:{
                System.out.println("写时钟");
                break;
            }
            case 0x41:{
                System.out.println("写参数");
                break;
            }
            case 0x42:{
                System.out.println("写网口IP地址");
                break;

            }
            case 0x43:{
                System.out.println("读参数");
                break;

            }
            case 0x44:{
                System.out.println("读系统信息");
                break;
            }
            case 0x45:{
                System.out.println("录波档案");
                break;
            }
            case 0x46:{
                System.out.println("报文档案");
                CdzlbPacket lbPacket = new CdzlbPacket();
                lbPacket.makeArc();
                Tio.send(channelContext, lbPacket);
                break;
            }
            case 0x47:{
                System.out.println("写系统信息");
                break;
            }
            case 0x48:{
                System.out.println("报文文件");
                break;
            }
            case 0x49:{
                System.out.println("网卡信息");
                break;
            }
            case 0x50:{
                System.out.println("索要整定数");
                break;
            }
            case 0x51:{
                System.out.println("索要cfg");
                break;
            }
            case 0x52:{
                System.out.println("索要dat");
                break;
            }
            case 0x53:{
                System.out.println("格式化SD卡");
                break;
            }
            case 0x54:{
                System.out.println("索要实时数据");
                break;
            }
            case 0x55:{
                System.out.println("索要充电文档");
                break;
            }


            default:
                System.out.println("没有发现任何规约中的命令");
                break;
        }

    }




}